package com.example.elmmerchants;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Base64;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.elmmerchants.First_Page_Fragment.Shop_Page;
import com.example.elmmerchants.Order_Setting.Book_Order_Setting;
import com.example.elmmerchants.Order_Setting.Set_Open_Shop_Time;
import com.example.elmmerchants.SQL.Connection_SQL;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Set_Open_Shop_Page extends AppCompatActivity {

    TextView shop_name, is_open_shop_text_view, is_open_shop_text_view_2, open_time, close_time, open_or_close_text_view, served_start_day, served_end_day, which_time_can_served, open_time_2, close_time_2;
    LinearLayout close_book_order, open_book_order, is_open_time_2, set_open_or_close_shop;
    RelativeLayout set_open_time, set_book_order;
    TextView start_day_text_view, end_day_text_view;
    ImageView shop_pic;

    String email, open_hour, close_hour, open_day, open_hour_2, close_hour_2, name;
    byte[] shop_pic_string = new byte[0];
    int can_served_start_time, can_served_end_time, is_open_shop, is_open_book_order, is_all_day_can_book_order;
    String[] start_day_list = new String[]{"0", "1", "2", "3", "4", "5", "6", "7"};
    String[] day_1 = new String[]{"1", "2", "3", "4", "5", "6", "7"};
    String[] day_2 = new String[]{"2", "3", "4", "5", "6", "7"};
    String[] day_3 = new String[]{"3", "4", "5", "6", "7"};
    String[] day_4 = new String[]{"4", "5", "6", "7"};
    String[] day_5 = new String[]{"5", "6", "7"};
    String[] day_6 = new String[]{"6", "7"};
    String[] day_7 = new String[]{"7"};
    boolean is_finish_update = false, is_loading_open_shop_page_data = false;

    private class Open_Shop_Thread extends Thread {
        @Override
        public void run() {
            is_loading_open_shop_page_data = false;

            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql = "SELECT * FROM merchant WHERE email = ?;";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, email);
                    ResultSet set = preparedStatement.executeQuery();
                    while (set.next()) {
                        shop_pic_string = set.getBytes("shop_picture");
                    }
                    is_loading_open_shop_page_data = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_loading_open_shop_page_data) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Bitmap decodedImage = BitmapFactory.decodeByteArray(shop_pic_string, 0, shop_pic_string.length);
                    shop_pic.setImageBitmap(decodedImage);
                }
            });
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_open_shop_page);

        email = getIntent().getStringExtra("email");
        is_open_shop = getIntent().getIntExtra("is_open_shop", 0);
        open_hour = getIntent().getStringExtra("open_hour");
        close_hour = getIntent().getStringExtra("close_hour");
        can_served_start_time = getIntent().getIntExtra("can_served_start_time", 0);
        can_served_end_time = getIntent().getIntExtra("can_served_end_time", 0);
        is_open_book_order = getIntent().getIntExtra("is_open_book_order", 0);
        is_all_day_can_book_order = getIntent().getIntExtra("is_all_day_can_book_order", 0);
        open_day = getIntent().getStringExtra("open_day");
        open_hour_2 = getIntent().getStringExtra("open_hour_2");
        close_hour_2 = getIntent().getStringExtra("close_hour_2");
        name = getIntent().getStringExtra("shop_name");

        is_open_shop_text_view = findViewById(R.id.is_open_shop);
        is_open_shop_text_view_2 = findViewById(R.id.is_open_shop_text_view);
        open_time = findViewById(R.id.open_time);
        close_time = findViewById(R.id.close_time);
        served_start_day = findViewById(R.id.served_start_day);
        served_end_day = findViewById(R.id.served_end_day);
        which_time_can_served = findViewById(R.id.which_time_can_served);
        open_book_order = findViewById(R.id.open_book_order);
        close_book_order = findViewById(R.id.close_book_order);
        set_open_time = findViewById(R.id.set_open_time);
        set_book_order = findViewById(R.id.set_book_order);
        is_open_time_2 = findViewById(R.id.is_open_time_2);
        open_time_2 = findViewById(R.id.open_time_2);
        close_time_2 = findViewById(R.id.close_time_2);
        set_open_or_close_shop = findViewById(R.id.set_open_or_close_shop);
        open_or_close_text_view = findViewById(R.id.open_or_close_text_view);
        shop_pic = findViewById(R.id.shop_pic);
        shop_name = findViewById(R.id.shop_name);

        Open_Shop_Thread openShopThread = new Open_Shop_Thread();
        openShopThread.start();

        shop_name.setText(name);
        System.out.println(open_hour_2.length());

        if (!open_hour_2.isEmpty()) {
            is_open_time_2.setVisibility(View.VISIBLE);
            open_time_2.setText(open_hour_2);
            close_time_2.setText(close_hour_2);
        }
        else {
            is_open_time_2.setVisibility(View.GONE);
        }

        if (is_open_shop == 1) {
            is_open_shop_text_view.setText("营业中");
            is_open_shop_text_view_2.setText("本店目前正常营业中。");
            open_or_close_text_view.setText("停止营业");
        }
        else {
            is_open_shop_text_view.setText("休息中");
            is_open_shop_text_view_2.setText("本店目前休息中。");
            open_or_close_text_view.setText("开始营业");
        }

        open_time.setText(open_hour);
        close_time.setText(close_hour);
        served_start_day.setText(String.valueOf(can_served_start_time));
        served_end_day.setText(String.valueOf(can_served_end_time));

        if (is_open_book_order == 1) {
            close_book_order.setVisibility(View.GONE);
            open_book_order.setVisibility(View.VISIBLE);
        }
        else {
            open_book_order.setVisibility(View.GONE);
            close_book_order.setVisibility(View.VISIBLE);
        }

        if (is_all_day_can_book_order == 1) {
            which_time_can_served.setText("休息时支持预订");
        }
        else {
            which_time_can_served.setText("仅营业时支持预订");
        }

        set_open_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Set_Open_Shop_Page.this, Set_Open_Shop_Time.class);
                intent.putExtra("email", email);
                intent.putExtra("open_day", open_day);
                intent.putExtra("open_time", open_hour);
                intent.putExtra("close_time", close_hour);
                startActivityForResult(intent, 1);
            }
        });

        if (is_open_book_order == 1) {
            set_book_order.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    set_which_time_can_give_order_dialog();
                }
            });
        }

        set_open_or_close_shop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                is_finish_update = false;

                if (is_open_shop == 1) {
                    ExecutorService executorService = Executors.newSingleThreadExecutor();
                    executorService.execute(() -> {
                        try {
                            Connection_SQL userSQL = new Connection_SQL();
                            Connection connection = userSQL.connection();
                            String sql = "update `merchant` set is_open = ? where email = ?";
                            PreparedStatement preparedStatement = connection.prepareStatement(sql);
                            preparedStatement.setInt(1, 0);
                            preparedStatement.setString(2, email);
                            preparedStatement.executeUpdate();
                            is_finish_update = true;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });

                    while (!is_finish_update) {
                        try {
                            Thread.sleep(1);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    Intent intent = new Intent(Set_Open_Shop_Page.this, Shop_Page.class);
                    intent.putExtra("is_open_shop", "休息中");
                    setResult(1, intent);
                    finish();
                }
                else {
                    ExecutorService executorService = Executors.newSingleThreadExecutor();
                    executorService.execute(() -> {
                        try {
                            Connection_SQL userSQL = new Connection_SQL();
                            Connection connection = userSQL.connection();
                            String sql = "update `merchant` set is_open = ? where email = ?";
                            PreparedStatement preparedStatement = connection.prepareStatement(sql);
                            preparedStatement.setInt(1, 1);
                            preparedStatement.setString(2, email);
                            preparedStatement.executeUpdate();
                            is_finish_update = true;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });

                    while (!is_finish_update) {
                        try {
                            Thread.sleep(1);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    Intent intent = new Intent(Set_Open_Shop_Page.this, Shop_Page.class);
                    intent.putExtra("is_open_shop", "营业中");
                    setResult(1, intent);
                    finish();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1: {
                if (data != null) {
                    open_hour = data.getStringExtra("open_time");
                    close_hour = data.getStringExtra("end_time");
                    open_hour_2 = data.getStringExtra("open_time_2");
                    close_hour_2 = data.getStringExtra("end_time_2");
                    if (!open_hour_2.isEmpty()) {
                        is_open_time_2.setVisibility(View.VISIBLE);
                        open_time.setText(open_hour);
                        close_time.setText(close_hour);
                        open_time_2.setText(open_hour_2);
                        close_time_2.setText(close_hour_2);
                    }
                    else {
                        is_open_time_2.setVisibility(View.GONE);
                        open_time.setText(open_hour);
                        close_time.setText(close_hour);
                    }
                }
            }
        }
    }

    void set_which_time_can_give_order_dialog() {
        Dialog dialog = new Dialog(this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.choose_can_give_order_bottomsheet);
        start_day_text_view = dialog.findViewById(R.id.start_day_text_view);
        start_day_text_view.setText("第0天");
        end_day_text_view = dialog.findViewById(R.id.end_day_text_view);
        end_day_text_view.setText("第0天");
        NumberPicker start_day = dialog.findViewById(R.id.start_day);
        start_day.setDisplayedValues(start_day_list);
        start_day.setMaxValue(start_day_list.length - 1);
        start_day.setMinValue(0);
        start_day.setValue(0);
        NumberPicker end_day = dialog.findViewById(R.id.end_day);
        start_day.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker numberPicker, int i, int i1) {
                start_day_text_view.setText("第" + numberPicker.getValue() + "天");
                end_day_text_view.setText("第" + numberPicker.getValue() + "天");

                if (numberPicker.getValue() == 0) {
                    end_day.setDisplayedValues(null);
                    end_day.setMaxValue(start_day_list.length - 1);
                    end_day.setDisplayedValues(start_day_list);
                    end_day.setMinValue(0);
                    end_day.setValue(0);
                }
                else if (numberPicker.getValue() == 1) {
                    end_day.setDisplayedValues(null);
                    end_day.setMaxValue(day_1.length - 1);
                    end_day.setDisplayedValues(day_1);
                    end_day.setMinValue(0);
                    end_day.setValue(0);
                }
                else if (numberPicker.getValue() == 2) {
                    end_day.setDisplayedValues(null);
                    end_day.setMaxValue(day_2.length - 1);
                    end_day.setDisplayedValues(day_2);
                    end_day.setMinValue(0);
                    end_day.setValue(0);
                }
                else if (numberPicker.getValue() == 3) {
                    end_day.setDisplayedValues(null);
                    end_day.setMaxValue(day_3.length - 1);
                    end_day.setDisplayedValues(day_3);
                    end_day.setMinValue(0);
                    end_day.setValue(0);
                }
                else if (numberPicker.getValue() == 4) {
                    end_day.setDisplayedValues(null);
                    end_day.setMaxValue(day_4.length - 1);
                    end_day.setDisplayedValues(day_4);
                    end_day.setMinValue(0);
                    end_day.setValue(0);
                }
                else if (numberPicker.getValue() == 5) {
                    end_day.setDisplayedValues(null);
                    end_day.setMaxValue(day_5.length - 1);
                    end_day.setDisplayedValues(day_5);
                    end_day.setMinValue(0);
                    end_day.setValue(0);
                }
                else if (numberPicker.getValue() == 6) {
                    end_day.setDisplayedValues(null);
                    end_day.setMaxValue(day_6.length - 1);
                    end_day.setDisplayedValues(day_6);
                    end_day.setMinValue(0);
                    end_day.setValue(0);
                }
                else if (numberPicker.getValue() == 7) {
                    end_day.setDisplayedValues(null);
                    end_day.setMaxValue(day_7.length - 1);
                    end_day.setDisplayedValues(day_7);
                    end_day.setMinValue(0);
                    end_day.setValue(0);
                }
            }
        });
        end_day.setMaxValue(start_day_list.length - 1);
        end_day.setDisplayedValues(start_day_list);
        end_day.setMinValue(0);
        end_day.setValue(0);
        end_day.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker numberPicker, int i, int i1) {
                int day = numberPicker.getValue() + start_day.getValue();
                end_day_text_view.setText("第" + day + "天");
            }
        });
        Button close_page = dialog.findViewById(R.id.close_page);
        close_page.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        Button save = dialog.findViewById(R.id.save);
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                can_served_start_time = start_day.getValue();
                can_served_end_time = end_day.getValue();
                served_start_day.setText(String.valueOf(can_served_start_time));
                served_end_day.setText(String.valueOf(can_served_end_time));

                ExecutorService executorService = Executors.newSingleThreadExecutor();
                executorService.execute(() -> {
                    try {
                        Connection_SQL userSQL = new Connection_SQL();
                        Connection connection = userSQL.connection();
                        String sql = "update `merchant_book_order_setting` set can_served_start_time = ?, can_served_end_time = ? where email = ?";
                        PreparedStatement preparedStatement = connection.prepareStatement(sql);
                        preparedStatement.setInt(1, start_day.getValue());
                        preparedStatement.setInt(2, end_day.getValue());
                        preparedStatement.setString(3, email);
                        preparedStatement.executeUpdate();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    runOnUiThread(() -> {
                        try {
                            Thread.sleep(100);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        dialog.dismiss();
                    });
                });
            }
        });

        dialog.show();
        dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
        dialog.getWindow().setGravity(Gravity.BOTTOM);
    }
}